/* 客户利润统计页面
 * @Author: Setsuna
 * @Email: 601890383@qq.com
 * @FilePath: \src\pages\CustomerManage\ProfitStatistics\List\index.tsx
 * @Date: 2021-12-06 16:48:42
 * @LastEditTime: 2021-12-07 16:40:30
 */

import React, { createRef } from 'react'
import {
  BaseListPage,
  http,
  IBaseListPageState,
  IBaseListPageProps,
  UdDrawer,
  uaaApp,
  IUdFormItem,
  columnRenders,
} from '@/lib'
import { Button, DatePicker, Input, InputNumber, message, Select, Spin, TreeSelect } from 'antd'
import udMainStore from '@/store/UdMain'
import UdSelect from '@/components/UdFormControls/UdSelect'
import apis from '@/apis/CustomerManage'
import comApis from '@/apis'
import dayjs from 'dayjs'
import { reaction } from 'mobx'
import { downBlobFile } from '@/utils/methods'

const exportBtn = 'user_customer_Profit_statistics_export'
export default class ProfitStatistics extends BaseListPage<ProfitStatisticsProps, ProfitStatisticsState> {
  protected useConditionsField = true
  // 隐藏掉头曲二曲
  // public hideArr: any = ['头曲', '二曲', '泸州老窖头曲酒类销售有限公司', '泸州老窖二曲酒类销售有限公司']
  // public brandList = udMainStore.brandList.filter(item => this.hideArr.indexOf(item.title) === -1)
  public brandList = udMainStore.brandList
  constructor(props) {
    super(props)
    this.state = {
      yearList: [],
      title: '客户利润统计',
      queryApi: apis.getProfitReportingCount,
      method: 'POST',
      rowKey: 'id',
      conditions: [
        {
          label: '品牌公司',
          id: 'brandCode',
          initialValue: this.brandList[0].value,
          render: <UdSelect showSearch allowClear={false} options={this.brandList} />,
        },
        {
          label: '年度',
          id: 'yearStr',
          initialValue: dayjs().year() + '',
          render: () => <UdSelect options={this.state.yearList} showSearch allowClear={false} />,
        },
        { label: '物料编码', id: 'materialCode' },
        { label: '物料名称', id: 'materialName' },
        { label: '客户编码', id: 'customerCode' },
        { label: '客户名称', id: 'customerName' },
      ],
      columns: [
        ['序号', 'id', (text, record, index) => index + 1, { minWidth: '30px' }],
        { title: '品牌公司', dataIndex: 'brandName', minWidth: '160px' },
        { title: '客户编码', dataIndex: 'customerCode', minWidth: '100px' },
        { title: '客户名称', dataIndex: 'customerName', minWidth: '140px' },
        { title: '物料编号', dataIndex: 'materialCode', minWidth: '120px' },
        { title: '物料名称', dataIndex: 'materialName', minWidth: '150px' },
        { title: '年度', dataIndex: 'yearStr', minWidth: '50px' },
        {
          title: '销售额',
          dataIndex: 'salesVolume',
          minWidth: '90px',
          render: (text, record, index) => this.renderInput(text, record, index, 'salesVolume'),
        }, //可改
        { title: '税前总利润', dataIndex: 'preGrossProfit', minWidth: '90px' },
        { title: '销售毛利', dataIndex: 'salesGrossProfit', minWidth: '100px' },
        { title: '其他收入', dataIndex: 'otherIncome', minWidth: '100px' },
        { title: '固定成本', dataIndex: 'fixedCost', minWidth: '100px' },
        { title: '营运资金（月均）', dataIndex: 'allCashMonth', minWidth: '140px' },
        { title: '现金', dataIndex: 'allCash', minWidth: '100px' },
        { title: '库存', dataIndex: 'allStock', minWidth: '100px' },
        { title: '填报库存月均（件）', dataIndex: 'allStockMonth', minWidth: '140px' },
        { title: '应收账款', dataIndex: 'allAccountsRec', minWidth: '100px' },
        {
          title: '应收账款（参考值）',
          dataIndex: 'accountsReceivableReference',
          minWidth: '140px',
          render: (text, record, index) => this.renderInput(text, record, index, 'accountsReceivableReference'),
        }, //可改
        { title: '其他应收款', dataIndex: 'allOtherRec', minWidth: '100px' },
        { title: '应付账款', dataIndex: 'allAccountsPay', minWidth: '100px' },
        { title: '净利率(%)', dataIndex: 'netMargin', minWidth: '100px' },
        { title: 'ROI(%)', dataIndex: 'roi', minWidth: '100px' },
        {
          title: '考核ROI(%)',
          dataIndex: 'checkRoi',
          minWidth: '100px',
          render: (text, record, index) => this.renderInput(text, record, index, 'checkRoi'),
        }, //可改
        {
          title: '操作',
          dataIndex: 'edit',
          key: 'edit',
          minWidth: '100px',
          fixed: 'right',
          render: columnRenders.operate([
            {
              title: '编辑',
              action: (text, record, index) => {
                this.edit(record)
              },
              show: (text, record, index) => {
                return !!!record.edit
              },
            },
            {
              title: '保存',
              action: (text, record, index) => {
                this.handleSave(record, index)
              },
              show: (text, record, index) => {
                return !!record.edit
              },
            },
            {
              title: '取消',
              action: (text, record, index) => {
                this.handCancel(record)
              },
              show: (text, record, index) => {
                return !!record.edit
              },
            },
          ]),
        },
      ],
      tableProps: {
        rowKey: 'id',
        scroll: { x: true },
        rowSelection: null,
      },
      leftBtns: [
        uaaApp.canUse(exportBtn) && (
          <Button type="primary" onClick={this.handDownloadExcel}>
            导出
          </Button>
        ),
      ],
      uploading: false,
      downloading: false,
      editArr: [],
    }
  }

  componentDidMount() {
    super.componentDidMount()
    this.getYearList()
  }

  private handUpdateTableRecord = record => {
    http.post(apis.updateProfitReporting, record).then(res => {
      message.success('操作成功')
      this.setState({ editArr: [] })
      this.query()
    })
  }

  private handDownloadExcel = () => {
    this.setState({ downloading: true })
    http
      .post(
        apis.downProfitReportingCountExcel,
        { conditions: { ...this.queryParams.conditions } },
        { responseType: 'arraybuffer' }
      )
      .then(res => {
        if (!res.data.code) {
          downBlobFile(res.data, `客户利润统计`)
        }
      })
      .finally(() => {
        this.setState({ downloading: false })
      })
  }

  private renderInput = (text, record, index, field) => {
    const { editArr } = this.state
    if (record.edit) {
      if (field === 'checkRoi') {
        return (
          <InputNumber
            style={{ width: '100%' }}
            value={editArr[index] && editArr[index][field] ? editArr[index][field] : record[field]}
            min={0}
            max={100}
            formatter={value => {
              const reg = /^(-)*(\d+)\.(\d\d).*$/
              const val = String(value).replace(reg, '$1$2.$3')
              return `${val}%`
            }}
            parser={value => {
              const reg = /^(-)*(\d+)\.(\d\d).*$/
              const val = String(value).replace(reg, '$1$2.$3')
              return val.replace('%', '')
            }}
            onChange={value => this.inputChange(value, record, index, field)}
          />
        )
      } else {
        return (
          <InputNumber
            style={{ width: '100%' }}
            value={editArr[index] && editArr[index][field] ? editArr[index][field] : record[field]}
            min={0}
            formatter={value => {
              const reg = /^(-)*(\d+)\.(\d\d).*$/
              const val = String(value).replace(reg, '$1$2.$3')
              return val
            }}
            parser={value => {
              const reg = /^(-)*(\d+)\.(\d\d).*$/
              const val = String(value).replace(reg, '$1$2.$3')
              return val
            }}
            onChange={value => this.inputChange(value, record, index, field)}
          />
        )
      }
    } else {
      return text
    }
  }

  private edit = record => {
    const { dataSource, editArr } = this.state
    const newArr = [...dataSource]
    const newEditArr = [...editArr]
    const inx = newArr.findIndex(item => item.id === record.id)
    newArr.splice(inx, 1, { ...record, edit: true })
    newEditArr[inx] = { ...record }
    this.setState({ dataSource: newArr, editArr: newEditArr })
  }

  private inputChange = (value, record, index, field) => {
    let { editArr } = this.state
    const newRecord = { ...record }
    newRecord[field] = value
    if (editArr[index]) {
      editArr[index][field] = value
    } else {
      editArr[index] = { ...newRecord }
    }
    this.setState({ editArr })
  }

  private handleSave = (record, index) => {
    const { editArr } = this.state
    this.handUpdateTableRecord(editArr[index])
  }

  private handCancel = record => {
    const { dataSource, editArr } = this.state
    const newArr = [...dataSource]
    const newEditArr = [...editArr]
    const index = newArr.findIndex(item => item.id === record.id)
    newArr.splice(index, 1, { ...newArr[index], edit: false })
    newEditArr.splice(index, 1)
    this.setState({ dataSource: newArr, editArr: newEditArr })
  }

  private getYearList = () => {
    http.get(comApis.GetQuotaAssessYearList).then(res => {
      const yearList = res.data?.map(({ year: value, name: title }) => ({ value: value + '', title })) || []
      this.setState({ yearList })
    })
  }

  render() {
    return (
      <Spin
        spinning={this.state.uploading || this.state.downloading}
        tip={this.state.uploading ? '上传中，请稍后...' : '请求中，请稍后...'}
      >
        {super.render()}
      </Spin>
    )
  }
}

interface ProfitStatisticsState extends IBaseListPageState {
  uploading: boolean
  downloading: boolean
  yearList: any[]
  editArr?: any[]
}

interface ProfitStatisticsProps extends IBaseListPageProps {}
